<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="0">
        <el-divider content-position="left"
          ><span class="head-divider"> 抢购全局设置</span></el-divider
        >
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="false"
          v-show="showSearch"
        >
          <el-form-item label="提前展示时间设置" prop="queryGoodsName">
            <el-radio-group v-model="form.showGoodsTime">
              <el-radio
                v-for="dict in goodsShowTimeList"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Warning" @click="handleQuery"
              >一键下架</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="24">
        <el-divider content-position="left"
          ><span class="head-divider">抢购商品列表</span></el-divider
        >
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
        >
          <el-form-item label="商品名称" prop="queryGoodsName">
            <el-input
              v-model="queryParams.queryGoodsName"
              placeholder="模糊查询按商品名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="画师" prop="queryPainterName">
            <el-input
              v-model="queryParams.queryPainterName"
              placeholder="模糊查询按画师昵称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['business:goods:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['business:goods:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['business:goods:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="pageList"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="100"
          />
          <el-table-column
            label="图片"
            align="center"
            prop="goodsSrc"
            width="100"
          >
            <template #default="scope">
              <el-image
                v-if="scope.row.goodsSrc"
                style="width: 100px; height: 100px"
                :src="uploadShowUrl + scope.row.goodsSrc"
                :preview-teleported="true"
                :preview-src-list="[uploadShowUrl + scope.row.goodsSrc]"
                :initial-index="0"
                fit="contain"
              />
              <div
                v-else
                style="width: 100px; height: 100px; line-height: 100px"
              >
                未上传图片
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="商品名称"
            align="center"
            width="300"
            prop="goodsName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="画师"
            align="center"
            prop="painterName"
            width="150"
          />
          <el-table-column
            label="业务类别"
            align="center"
            prop="name"
            width="150"
          />
          <el-table-column
            width="100"
            label="上架/下架"
            align="center"
            prop="upStatus"
          >
            <template #default="scope">
              <dict-tag :options="stutasList" :value="scope.row.upStatus" />
            </template>
          </el-table-column>
          <el-table-column
            label="价格"
            align="center"
            prop="goodsPrice"
            width="100"
            sortable
          />
          <el-table-column
            label="抢购总量"
            align="center"
            prop="openSaleSum"
            width="100"
          />
          <el-table-column
            label="排序"
            align="center"
            prop="sort"
            width="100"
          />
          <el-table-column
            label="抢购日期"
            align="center"
            prop="openSaleTime"
            width="200"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.openSaleTime, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createdAt"
            width="200"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            prop="updatedAt"
            width="200"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.updatedAt, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="300"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleOpenSub(scope.row)"
                v-hasPermi="['business:goods:edit']"
                >查看</el-button
              >
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:goods:edit']"
                >修改</el-button
              >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:goods:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 选择商品 -->
    <el-dialog :title="title" v-model="open" width="580px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="painterId">
              <div v-if="!form.goodsName" class="txt-999">请选择商品名称</div>
              <div v-else>{{ form.goodsName }}</div>
              <el-button
                v-show="title == '新增'"
                class="btn"
                type="primary"
                @click="handleOpenModal"
                >选择</el-button
              >
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <!-- <el-form-item label="开始抢购的时间" prop="openSaleTime">
              <el-date-picker
                v-model="form.openSaleTime"
                type="datetime"
                placeholder="请输入开始售卖日期"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item> -->
            <el-form-item label="设置抢购开始时间" prop="openSaleTime">
              <el-input v-model="form.openSaleTime" :min="0" :max="60" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="价格" prop="price">
              <el-input-number
                disabled
                v-model="form.price"
                :min="0"
                :max="999999"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="抢购数量" prop="openSaleSum">
              <el-input-number
                v-model="form.openSaleSum"
                :min="0"
                :max="999999"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上下架" prop="upStatus">
              <el-radio-group v-model="form.upStatus">
                <el-radio
                  v-for="dict in upStatusList"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="1" :max="99999" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="选择商品" v-model="openSub" width="80%" append-to-body>
      <Modal @change="handleGetSub" />
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog
      :title="detailTitle"
      v-model="openSub1"
      width="980px"
      append-to-body
    >
      <el-table v-loading="loadingSub" :data="pageListSub" max-height="600">
        <el-table-column label="序号" align="center" type="index" width="100" />
        <el-table-column label="点击人" align="center" prop="pointerUserQQ" />
        <el-table-column label="使用人" align="center" prop="userQQ" />
        <el-table-column label="昵称" align="center" prop="nickname" />
        <el-table-column
          label="审核状态"
          align="center"
          prop="status"
          width="150"
        >
          <template #default="scope">
            <dict-tag :options="approveStatusList" :value="scope.row.status" />
          </template>
        </el-table-column>

        <el-table-column label="抢购时间" align="center" prop="createdAt">
          <template #default="scope">
            <span>{{
              parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { updateGoods, deleteGoods } from "@/api/business/goods";
import {
  listGoodsCategory,
  addGoodsCategory,
  updateGoodsCategory,
  deleteGoodsCategory,
  getSeckillListAll,
} from "@/api/goods/seckill";

import { listPainter } from "@/api/business/painter";
import { listAllOrder } from "@/api/business/order";
import { useDebounceFn } from "@vueuse/core";
import Modal from "./modal.vue";

const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadCos/goods";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;
const imageUrl = ref("");

const pageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailTitle = ref(""); // 详情标题栏

const painterList = ref([]); // 画师下拉框
// 状态 0 创建   1补充信息   2审核通过    3不通过
const approveStatusList = ref([
  {
    label: "不通过",
    value: "3",
    elTagClass: "",
    elTagType: "danger",
  },
  {
    label: "审核通过，订单已生成",
    value: "2",
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "待审核",
    value: "1",
    elTagClass: "",
    elTagType: "warning",
  },
  {
    label: "待完善信息",
    value: "0",
    elTagClass: "",
    elTagType: "danger",
  },
]);
const useOtherPlatformList = ref([
  { label: "是", value: "是" },
  { label: "否", value: "否" },
]);
const statusList = ref([
  { label: "可以转让", value: 1 },
  { label: "禁止转让", value: 2 },
]);
const goodsShowTimeList = ref([
  { label: "6小时", value: 6 },
  { label: "12小时", value: 12 },
  { label: "24小时", value: 24 },
  { label: "48小时", value: 48 },
]);
const upStatusList = ref([
  { label: "上架", value: 1 },
  { label: "下架", value: 2 },
]);
const typeList = ref([
  { label: "限时", value: 0 },
  { label: "限量", value: 1 },
]);
const openSub = ref(false); // 查看购买详情
const openSub1 = ref(false); // 查看购买详情
const loadingSub = ref(false);
const pageListSub = ref([]);

const data = reactive({
  stutasList: [
    {
      label: "上架",
      value: "1",
      elTagClass: "",
      elTagType: "success",
    },
    {
      label: "下架",
      value: "2",
      elTagClass: "",
      elTagType: "danger",
    },
  ],

  form: {
    upStatus: 1,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryGoodsName: undefined,
    queryPainterName: undefined,
    orderType: undefined,
    orderName: undefined,
  },
  rules: {
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "change" },
    ],
    openSaleTime: [
      { required: true, message: "售卖日期不能为空", trigger: "change" },
    ],
    openSaleSum: [
      { required: true, message: "抢购数量不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules, stutasList } = toRefs(data);

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be PNG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
function onSuccessImg(response) {
  if (response.code == 200) {
    form.value.src = response.data;
    imageUrl.value = uploadShowUrl + response.data;
  }
}
/** 查询画师列表 */
function getPainterList() {
  // loading.value = true;
  listPainter().then((response) => {
    painterList.value = response.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    // loading.value = false;
  });
}

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listGoodsCategory(queryParams.value).then((response) => {
    pageList.value = response.data.rows;
    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    painterId: undefined,
    saleTime: undefined,
    openSaleTime: undefined,
    price: 0,
    saleSum: 0,
    status: 1,
    upStatus: 1,
    type: 1,
    src: "",
    useOtherPlatform: "是",
  };
  imageUrl.value = null;
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.orderType = undefined;
  queryParams.value.orderName = undefined;
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}
/** 查看详情 */
function handleRead() {}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form.value = {
      id: arr[0].id,
      goodsName: arr[0].goodsName,
      goodsId: arr[0].goodsId,
      price: arr[0].goodsPrice,
      openSaleTime: arr[0].openSaleTime,
      openSaleSum: arr[0].openSaleSum,
      sort: arr[0].sort,
      upStatus: arr[0].upStatus,
    };
  } else {
    let openSaleTime = proxy.parseTime(
      row.openSaleTime,
      "{y}-{m}-{d} {h}:{i}:{s}"
    );

    form.value = {
      id: row.id,
      goodsName: row.goodsName,
      goodsId: row.goodsId,
      price: row.goodsPrice,
      openSaleTime: openSaleTime,
      openSaleSum: row.openSaleSum,
      sort: row.sort,
      upStatus: row.upStatus,
    };
  }

  open.value = true;
  title.value = "修改";
}
// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateGoodsCategory(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoodsCategory(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }
  let arrList = pageList.value.filter((item) => {
    return;
  });
  proxy.$modal
    .confirm('是否确认删除编号为"' + deleteId + '"的数据项？')
    .then(function () {
      return deleteGoodsCategory({ ids: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 查看购买详情 */
function handleOpenSub(row) {
  openSub1.value = true;
  loadingSub.value = true;
  let sendJson = {
    categoryId: row.id,
  };
  getSeckillListAll(sendJson).then((response) => {
    pageListSub.value = response.data;
    detailTitle.value =
      "抢购详情: " +
      row.goodsName +
      " - " +
      row.painterName +
      " - 总数：" +
      response.data.length +
      "份";
    loadingSub.value = false;
  });
}

function handleChangeType(params) {
  let arr = typeList.value.filter((item) => {
    return item.value == params;
  });
  if (arr && arr.length > 0) {
    return arr[0].label;
  } else {
    return " ";
  }
}
// 排序
function handleSortChange(column) {
  let data1;
  if (column.order == "ascending") {
    data1 = "ASC";
  } else if (column.order == "descending") {
    data1 = "DESC";
  }
  if (!data1) {
    data.queryParams.orderName = undefined;
  } else {
    data.queryParams.orderName = column.prop;
  }
  data.queryParams.orderType = data1;
  getList();
}
//
function handleOpenModal() {
  openSub.value = true;
}
// 获取选中商品的值
function handleGetSub(json) {
  openSub.value = false;
  data.form = {
    ...data.form,
    goodsName: json.goodsName,
    goodsId: json.id,
    price: json.price,
  };
}

getList();
getPainterList();
</script>
<style lang="scss" scoped>
.color-blue {
  color: rgb(0, 119, 255);
  cursor: pointer;
}
.avatar-uploader {
  width: 200px;
  height: 300px;
  .avatar {
    width: 100%;
    height: 100%;
  }
}
.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.head-divider {
  font-size: 18px;
  font-weight: 600;
}
.btn {
  margin-left: 20px;
}
.txt-999 {
  color: #ccc;
}
</style>
